package test.transferFile.codec;

import java.nio.charset.Charset;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolDecoderAdapter;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

import test.transferFile.common.MyBuffer;
import test.transferFile.common.MyFile;

public class TransferFileDecoder extends ProtocolDecoderAdapter {

  private Charset charset;

  public TransferFileDecoder(Charset charset) {
    this.charset=charset;
  }

  public void setCharset(Charset charset) {
    this.charset=charset;
  }

  public Charset getCharset() {
    return charset;
  }

  @Override
  public void decode(IoSession session, IoBuffer buf, ProtocolDecoderOutput out) throws Exception {
    MyBuffer myBuf=new MyBuffer(buf);
    String fileName=myBuf.getString();
    int length=myBuf.getInt();
    int pos=myBuf.getInt();
    //
    byte[] b=new byte[length];
    myBuf.get(b);
    IoBuffer data=IoBuffer.allocate(length);
    data.put(b);
    data.flip();
    //
    MyFile myFile=new MyFile();
    myFile.setName(fileName);
    myFile.setLength(length);
    myFile.setPos(pos);
    myFile.setData(data);
    out.write(myFile);
  }
}
